package com.cake.service.impl;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cake.base.config.Constant;
import com.cake.base.util.ReturnUtils;
import com.cake.dao.XxAdminMapper;
import com.cake.dao.XxMenuMapper;
import com.cake.dao.XxRoleMapper;
import com.cake.entity.XxAdmin;
import com.cake.entity.XxMenu;
import com.cake.entity.XxRole;
import com.cake.entity.pojo.LoginAdminInfo;
import com.cake.response.LoginResponse;
import com.cake.service.base.BaseService;
import com.cake.service.inter.IXxAdminService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 后天人员业务层
 * @author Administrator
 *
 */
@Service
@Transactional
public class XxAdminServiceImpl extends BaseService<XxAdmin> implements IXxAdminService{

	@Autowired
	private XxAdminMapper xxAdminMapper;
	
	@Autowired
	private XxMenuMapper XxMenuMapper;
	
	@Autowired
	private XxRoleMapper xxRoleMapper;
	
	@Override
	public LoginResponse loginForAdmin(XxAdmin xxAdmin, HttpServletRequest request) {
		LoginResponse loginResponse = new LoginResponse();
		XxAdmin selectAdmin = xxAdminMapper.selectAdminByUserNameAndPassword(xxAdmin);
		if (selectAdmin == null) {
			loginResponse.returnFail("用户名或密码不正确");
			return loginResponse;
		}
		LoginAdminInfo loginAdminInfo = new LoginAdminInfo();
		loginAdminInfo.setAdminId(selectAdmin.getId());
		loginAdminInfo.setRoles(xxRoleMapper.selectRolesByAdminId(selectAdmin.getId()));
		request.getSession().setAttribute(Constant.USER_SESSION_KEY, loginAdminInfo);
		loginResponse.returnSuccess();
		return loginResponse;
	}

	@Override
	public List<XxMenu> selectAdminMenus(Long adminId) {
		return XxMenuMapper.selectMenusByAdminId(adminId);
	}

	@Override
	public ReturnUtils selectSystemAdmins(XxAdmin xxAdmin) throws Exception {
		PageHelper.startPage(xxAdmin.getCurrentPage(), xxAdmin.getPageSize());
		List<XxAdmin> list = xxAdminMapper.selectByAttributeAnd(xxAdmin);
		PageInfo<XxAdmin> page = new PageInfo<>(list);
		return ReturnUtils.forNoramlPage("000000", list, 
				page.getPageNum(), page.getPageSize(), page.getPages(), (int)page.getTotal());
	}

	@Override
	public ReturnUtils selectSystemAdminById(Long adminId) {
		XxAdmin xxAdmin = xxAdminMapper.selectByPrimaryKey(adminId);
		List<XxRole> roles = xxRoleMapper.selectRolesByAdminId(adminId);
		String roleStr = "";
		for (int i = 0; i < roles.size(); i++) {
			if(i == roles.size() - 1){
				roleStr = roleStr + roles.get(i).getId();
			}else{
				roleStr = roleStr + roles.get(i).getId() + ",";
			}
		}
		xxAdmin.setRolesStr(roleStr);
		return ReturnUtils.forNoramlSuccess(xxAdmin);
	}

}
